#!/usr/bin/ruby

class TravisDepsBuilder
  def self.make(name)
    instance = klass.new(name)
    instance.fill_data
    instance.deps
    instance.build
  end

  def self.klass
    Module.const_get([self.name, self.os.capitalize].join)
  rescue NameError
    self
  end

  def self.os
    ENV['TRAVIS_OS_NAME']
  end

  attr_reader :name, :url, :action, :os

  def initialize(name)
    @name, @os = name, self.class.os
  end

  def fill_data
    data = build_map.fetch(name)
    @url, @action = data[:url], data[:action]
  end

  def build
    send(action)
  end

  def deps; end

  private
  def package_manager_update
    # yes class variable, you wanna update only once across all instances
    @@updated ||= false
    return if @@updated
    sh({'linux' => 'sudo apt-get update -y', 'osx' => 'brew update'}[os])
    @@updated = true
  end

  def package_install(*packages)
    cmd = {
      'linux' => 'sudo apt-get install %s -y',
      'osx'   => 'brew install %s'
    }[os] % [packages.join(" ")]

    sh cmd
  end

  def git
    sh "git clone --depth=1 #{url} #{name}"
    compile name
  end

  def stable
    filename = File.basename(url)
    sh "wget #{url}"
    sh "tar -xzvf #{filename}"
    dirname  = File.basename(url, ".tar.gz"  )
    compile dirname
  end

  def package
    package_install(url)
  end

  def compile(dirname)
    sh "cd #{dirname} && #{configure} && make && sudo make install"
    sh "cd $TRAVIS_BUILD_DIR"
  end

  def configure
    "./configure"
  end

  def sh(command)
    `#{command}`
  end
end

class Libav < TravisDepsBuilder
  def build_map
    {
      "libav-git" => {
        :action => :git,
        :url    => "git://git.libav.org/libav.git"
      },
      "ffmpeg-git" => {
        :action => :git,
        :url    => "https://github.com/FFmpeg/FFmpeg.git"
      }
    }
  end

  def configure
    [super, "--cc=#{ENV['CC']} --disable-asm"].join(" ")
  end
end

class LibavOsx < Libav
  def build_map
    {
      "ffmpeg-git" => { :action => :package, :url => 'ffmpeg' },
    }
  end
end

class Libass < TravisDepsBuilder
  def build_map
    {
      "libass-stable" => {
        :action => :stable,
        :url    => 'https://github.com/libass/libass/releases/download/0.12.1/libass-0.12.1.tar.gz'
      }
    }
  end
end

class Dependencies < TravisDepsBuilder
  def deps
    packages = {
      'linux' => 'pkg-config fontconfig libfribidi-dev yasm libxinerama-dev libxrandr-dev',
      'osx'   => 'pkg-config fontconfig freetype fribidi yasm'
    }
    package_manager_update
    package_install(packages.fetch(os))
  end
end

Dependencies.new(:deps).deps

Libass.make(ARGV[0])
Libav.make(ARGV[1])
